import requests
# from config.getConfig import config
from utils.jwt.gettoken import get_token
from utils.sql.app.user import insert_userinfo, get_userinfo


async def authorization(data):
    # 获取openid
    try:
        open_id = await get_openid(data.code)
        # print(open_id)
        if open_id['code'] == 200:
            # 如果拿到openid就获取token
            token = await get_token(open_id['data'])
            # # 拿到token之后，查询用户是否存在，
            # exist = is_user(open_id['data'])
            # print("token:", token)
            if token:
                # 向数据库添加数据
                datas = {
                    "id": open_id['data'],
                    "headimg": data.headimg,
                    "nickname": data.nickname,
                    "share_id": data.share_id
                }
                new_data = insert_userinfo(datas)
                if new_data['code'] == 200:
                    # # 获取个人信息
                    info = get_userinfo(open_id['data'])
                    print("个人信息：",info)
                    if info['code'] == 200:
                        return {
                            "code": 200,
                            "data": {
                                "token": token,
                                "userInfo": info['data'],
                            },
                            "message": "授权成功"
                        }
    except Exception as e:
        print(e)
        return {
            "code": 201,
            "data": e,
            "message": "授权失败"
        }



"""
获取OpenID
:param code 获取openID的code
:author scw 2024年3月5日
"""


async def get_openid(code: str):
    # secret = config('WeChat')['appsecret']
    req_data = {
        "appid": "wxd430af2afe03388a",
        "secret": "ab65844b183e0cb7d76f72958d74f9f2",
        "js_code": code,
        "grant_type": 'authorization_code'
    }
    try:
        response = requests.get('https://api.weixin.qq.com/sns/jscode2session', req_data)
        if response.status_code == 200:
            res = response.json()
            # 判断是否存在errcode字段
            err = res.get('errcode', False)
            if err:
                return {
                    "code": 201,
                    "data": res,
                    "message": '获取openID失败'
                }
            else:
                return {
                    "code": 200,
                    "data": res['openid'],
                    "message": '获取openID成功'
                }

    except requests.exceptions.RequestException as e:
        return {
            "code": 201,
            "data": e,
            "message": '获取openID失败'
        }
